﻿using System;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using TFMAPI;

namespace TwitterFollowersMonitor
{
    class TFMVersion
    {
        //The Twitter account used to inform about the current version of the software and get notificacions of new updates
        private const string GETVERSIONS_TWITTER_ACCOUNT = "TFMVersions";

        //Private constructor. Not allowing instantiation from outside the class.
        private TFMVersion() { }


        //The current version of the App (from the assembly)
        public Version CurrentVersion 
        {
            get
            {
                return new Version(Application.ProductVersion);
            }
        }

        public Version LastVersion { get; private set; }
        public string DownloadURL { get; private set; }

        /// <summary>
        /// Gets the information about the last published version.
        /// </summary>
        /// <returns>a TFMVersion object with version information</returns>
        /// <remarks>Gets the last version information from the specific Twitter account fos this.</remarks>
        public static TFMVersion GetLastVersionInfo()
        {

            TFMVersion vInfo = new TFMVersion(); 
            vInfo.LastVersion = vInfo.CurrentVersion;  //By default return current app version as the last one
            try
            {
                TwitterUserInfo statusTFM = TwitterAPIWrapper.GetTwitterUserInfo(GETVERSIONS_TWITTER_ACCOUNT);
                string lastStatus = statusTFM.status.text;
                //Current statuses informing about version have this structure:
                //#TFMonitor v:version yyyymmdd url:downloadurl
                //eg:
                //#TFMonitor v:1.0.0.0 url:http://TFM.codeplex.com/Releases/
                Regex vRE = new Regex(@"\#TFMonitor v:(?<version>\d\.\d\.\d\.\d) url:(?<URL>.*)",RegexOptions.IgnoreCase);
                Match m = vRE.Match(lastStatus);
                vInfo.LastVersion =  new Version(m.Groups["version"].Value);
                vInfo.DownloadURL = m.Groups["URL"].Value;
            }
            catch {}

            return vInfo;
        }
    }

}
